import React from "react";
import { Badge, Icon, Popover } from "antd";
import { withRouter } from "dva/router";
import queryString from "query-string";
import { setActiveMenu } from "utils/comm";
import styles from "./index.less";
import NoticeContent from "./NoticeContent";
import NoticeTitle from "./NoticeTitle";
import { openNotificationWithIcon } from "../../utils/comm";

@withRouter
class TopNotice extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      popoverVisible: false,
    };
  }

  // componentDidMount() {
  //   this.getNoticeList();
  // }

  componentWillUnmount() {}

  getNoticeList = () => {
    const { dispatch } = this.props;
    const params = { pageNum: 1, pageSize: 10, status: 0 };
    dispatch({ type: "PageNotice/getNoticeList", payload: params });
  };

  updateReadStatus = () => {
    const { dispatch } = this.props;
    dispatch({ type: "PageNotice/updateReadStatus", payload: {} }).then(
      ({ errCode, errMsg, errortext }) => {
        if (errCode === 0) {
          this.getNoticeList();
          return;
        }
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || errortext || "标记为已读失败",
        );
      },
    );
  };

  onVisibleChange = (visible) => {
    this.setState({ popoverVisible: visible });
    if (this.timer) {
      // 避免频繁的hover
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      this.getNoticeList();
    }, 1000);
    if (!visible) {
      // hover 不超过1秒，清楚定时器，不请求数据
      clearTimeout(this.timer);
    }
  };

  onHiddenPopover = (item) => {
    const { history, dispatch } = this.props;
    this.setState({ popoverVisible: false });
    if (item) {
      dispatch({
        type: "PageNotice/updateReadStatus",
        payload: { ids: [item.id] },
      }).then(({ errCode, errMsg, errortext }) => {
        if (errCode === 0) {
          this.getNoticeList();
          return;
        }
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || errortext || "标记为已读失败",
        );
      });
      history.push({
        pathname: "/message/detail",
        search: queryString.stringify({
          processInstanceId: item.processInstanceId,
          actionId: item.id,
        }),
      });
    } else {
      history.push({ pathname: "/message" });
    }
    setActiveMenu("message", "flow-home");
  };

  render() {
    const { history, noticeData, msgTypes } = this.props;
    const { popoverVisible } = this.state;
    const { noticeList, totalCount } = noticeData || {};
    return (
      <div
        className={styles.top_notice}
        style={{ marginRight: totalCount ? 5 : 0 }}
      >
        <Popover
          placement="bottomRight"
          trigger="hover"
          visible={popoverVisible}
          onVisibleChange={this.onVisibleChange}
          title={
            <NoticeTitle
              count={totalCount || 0}
              onMark={this.updateReadStatus}
            />
          }
          content={
            <NoticeContent
              count={totalCount || 0}
              data={noticeList || []}
              msgTypes={msgTypes}
              history={history}
              onHiddenPopover={this.onHiddenPopover}
            />
          }
        >
          <Badge count={totalCount || 0} showZero={false}>
            <Icon type="bell" />
          </Badge>
        </Popover>
      </div>
    );
  }
}
export default TopNotice;
